package com.neusoft.elm.framework;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;

@WebServlet("/")
public class DispatcherServlet extends HttpServlet{

	//胡恩玮3022244265
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//中文编码处理
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("application/json");
		//获取客户端请求路径
		String path = request.getServletPath();//根据请求路径进行总调度、分发处理
		//约定大于配置！ 我来解析你的请求！
		//根据请求路径，讲控制器类名和其中方法名解析出来
		String className = path.substring(1,path.lastIndexOf("/"));
		String methodName = path.substring(path.lastIndexOf("/")+1);//截取到最后
		PrintWriter out = null;
		try {
			//获取controller类的信息，然后通过描述类获取对象
			Class clazz = Class.forName("com.neusoft.elm.controller."+className);
			Object controller = clazz.getDeclaredConstructor().newInstance();//java1.9之后这样用
			Method method = clazz.getMethod(methodName,new Class[] {HttpServletRequest.class});
			//调用方法
			Object result = method.invoke(controller,new Object[] {request});
			
			out = response.getWriter();
			ObjectMapper om = new ObjectMapper();
			out.print(om.writeValueAsString(result));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("DispatcherServlet信息：Servlet请求路径："+path);
			System.out.println("DispatcherServlet信息：类名："+className+"\t方法名："+methodName);
		} finally {
			out.close();
		}
		
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		doGet(request, response);
	}
	
}
